const device = wx.getSystemInfoSync();// 获取手机型号信息
var twoPoint = {x1: 0,y1: 0,x2: 0,y2: 0}// 两个点的位置
import http from '../../utils/http'
Page({
  data: {
    time:0,
    number:0,
    img:'../../image/logo.png',
    option:[],  //方数数组
    list:[],
    btnType:1,
    car_type:2,
    car_code:'',
    imgCount:0,
    squareNumber:0,
    frequency:0,
    checkYuan:false,
    // checkYuan:1,
    imagePath:'',
    width: device.windowWidth,                //剪裁框的宽度
    height: device.windowHeight / 2,//剪裁框的长度
    originImg: null,                                //存放原图信息
    stv: {
      offsetX: 0,                                   //剪裁图片左上角坐标x
      offsetY: 0,                                   //剪裁图片左上角坐标y
      zoom: false,                                  //是否缩放状态
      distance: 0,                                  //两指距离
      scale: 1,                                     //缩放倍数
      rotate: 0                                     //旋转角度
    },
  },
  getconfig(){
    let that = this;

    http('/index/config','post',{}).then(res=>{
      that.setData({
        home:res.data.data.home
      })
      console.log(that.data);
    }).catch(res=>{
      console.log(res);
    })

  },
  closemodel2(){
    console.log(11);
    this.setData({
      close:1
    })
 },
  showmodel(){
    http('/user/close','post',{uid:wx.getStorageSync('uid')}).then(res=>{
      http('/index/index','post',{uid:wx.getStorageSync('uid')}).then(res=>{
        console.log(res);
        let end_time=res.data.data.end_time
        this.setData({
          close:res.data.data.close
        })
        if(end_time!=0){
          let time=new Date(end_time)
          this.setData({
            time
          })
          console.log(time);
        }
      
        this.setData({
          number:res.data.data.number
        })
      }).catch(res=>{
        console.log(res);
      })
    }).catch(res=>{
     
    })
  },
 
  onLoad: function (options) {
    this.getconfig()
    var uid = wx.getStorageSync('uid');
    if(uid){
      http('/index/index','post',{uid}).then(res=>{
        console.log(res);
        let end_time=res.data.data.end_time
        this.setData({
          close:res.data.data.close
        })
        if(end_time!=0){
          var date = new Date(end_time*1000);
          var year = date.getFullYear();
          console.log(year);
          var Y = date.getFullYear() + '-';
          var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
          var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
          var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
          var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
          var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
          
          let time = Y+M+D+h+m+s;

          this.setData({
            time
          })
          // console.log(time);
        }
      
        this.setData({
          number:res.data.data.number
        })
      }).catch(res=>{
        console.log(res);
      })
    }
    console.log("首页pid是",options);
    if(options.openID){
      wx.setStorageSync('pid', options.openID)
    }
    // console.log(uid);
  
   
    // var that = this
   
    // var img = wx.getStorageSync('img');
    // if(img != ''){
    //   this.setData({
    //     img:img
    //   })
    // }

    // if(uid != ''){
    //   wx.request({
    //     url: 'https://www.shumutou.com/api/index/index',
    //     method:'post',
    //     dataType:JSON,
    //     data: {
    //       uid: uid,
    //     },
    //     success:(res)=>{
    //       res = JSON.parse(res.data);
    //       console.log(res);
    //       that.setData({
    //         frequency:res.data.number
    //       })
    //     }
    //   })

    //   wx.request({
    //     url: 'https://www.shumutou.com/api/index/cube',
    //     method:'post',
    //     dataType:JSON,
    //     success:(res)=>{
    //       res = JSON.parse(res.data);
    //       that.setData({
    //         option:res.data
    //       })
    //     }
    //   })


    // }
  },
  onReady: function () {

  },
  toBuy(){
    if(!wx.getStorageSync('uid')){
      wx.switchTab({
        url: '/pages/loginpublic/loginpublic',
      })
      return
}
       wx.navigateTo({
         url: '/pages/buy/buy',
       })
  },
  toCalc(){
    wx.navigateTo({
      url: '/pages/counter/counter',
    })
  },
   getLocalTime(nS) {     
    return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/,' ');     
    },
  onShow: function () {
    this.getconfig()
    var uid = wx.getStorageSync('uid');
    if(uid){
      http('/index/index','post',{uid}).then(res=>{
        console.log(res);
        let end_time=res.data.data.end_time
        this.setData({
          close:res.data.data.close
        })
        if(end_time!=0){
          var date = new Date(end_time*1000);
          var year = date.getFullYear();
          console.log(year);
          var Y = date.getFullYear() + '-';
          var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
          var D = (date.getDate() < 10 ? '0'+date.getDate() : date.getDate()) + ' ';
          var h = (date.getHours() < 10 ? '0'+date.getHours() : date.getHours()) + ':';
          var m = (date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()) + ':';
          var s = (date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds());
          
          let time = Y+M+D+h+m+s;

          this.setData({
            time
          })
          // console.log(time);
        }
      
        this.setData({
          number:res.data.data.number
        })
      }).catch(res=>{
        console.log(res);
      })
    }
  },
  /**
   * 跳转单页
   */
  infoClick:function(){
    wx.navigateTo({
      url: '../jiaocheng/jiaocheng?id=1'
    })
  },
  // 上传图片
  uploadTap:function() {
    // let uid = wx.getStorageSync('uid');
    // if(uid == undefined || uid == ''){
    //   wx.navigateTo({
    //     url:'/pages/login/login',
    //   })
    //   return;
    // }
    //上传本地图片
    let _this = this
    if(!wx.getStorageSync('uid')){
          wx.switchTab({
            url: '/pages/login/login',
          })
          return
    }
    wx.chooseImage({
      count: 1, // 默认9
      sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success(res) {
        wx.showLoading({
          title: '加载中',
        })
        wx.getImageInfo({
          src: res.tempFilePaths[0],
          success:(res)=>{
            console.log(res);
            // if(res.height/res.width>1.5){
            //   wx.showToast({
            //     title: '请上传1：1.5得图',
            //   })
            //   return
            // }
          }
        })
        wx.uploadFile({
          url: 'https://www.shumutou.com/api/upload/uploadFile',
          filePath: res.tempFilePaths[0],
          name: 'file',
          success (res2){
            wx.hideLoading()
            var res2 = JSON.parse(res2.data);
            console.log(res2);
            if(res2.success == 1){
              // _this.initImg(res2.tips.url);
              // _this.setData({
              //   imagePath:res2.tips.url,
              //   imageUrl:res2.tips.name,
              //   btnType:2,
              //   list:[]
              // })
             wx.navigateTo({
               url: '/pages/result/result?imageUrl='+res2.tips.name+"&imagePath="+res2.tips.url,
             })
            }else{
              wx.showToast({  
                title: '上传失败',  
                icon: 'error',  
                duration: 2000  
              }) 
            }
            
            console.log(res2);
            return;
          }
        })
      }
    })
  },

  // 开始识别图片
  woodStart:function(){
    let _this = this
    let uid = wx.getStorageSync('uid');
    let img = _this.data.imageUrl;
    if(uid == undefined || uid == ''){
      wx.navigateTo({
        url:'/pages/loginpublic/loginpublic',
      })
      return;
    }
    wx.showLoading({
      title: '识别中',
    })
    wx.request({
      url: 'https://www.shumutou.com/api/index/mutou',
      method:'post',
      dataType:JSON,
      data: {
        uid: uid,
        img:img
      },
      success:(res)=>{
        res = JSON.parse(res.data);
        console.log(res);
        if(res.success == 1){
          _this.see_all(res.data);
          _this.setData({
            imgCode:res.data
          })
          // wx.navigateTo({
          //   url:'/pages/result/result',
          // })
        }else{
          wx.showToast({  
            title: res.tips,  
            icon: 'error',  
            duration: 2000  
          }) 
        }
      }
    })
    
  },
  see_all:function(code){
    console.log(123);
    let _this = this;
    wx.request({
      url: 'https://www.shumutou.com/api/index/see',
      method:'post',
      dataType:JSON,
      data: {
        code:code
      },
      success:(res)=>{
        res = JSON.parse(res.data);
        if(res.success == 1){
          wx.hideLoading()
          console.log(res.data)
          var width = parseFloat(_this.data.originImg.width / res.weight);
          console.log(_this.data.originImg.width)
          console.log(res.weight)
          console.log(width)

          var list = res.data
          var newlist = [];
          for(var i = 0; i<list.length;i++){
            var r = parseFloat(list[i][2] * width);
            var x = parseFloat(list[i][0] * width - r);
            var y = parseFloat(list[i][1] * width - r);
           
            var arr = [x,y,r];
            newlist.push(arr)
          }
          console.log(newlist);
          _this.setData({
            list:newlist,
            btnType:3,
            imgCount:newlist.length
          })
        }else if(res.success == 3){
          setTimeout(function() {
            _this.see_all(code);
          }, 5000);
        }else{
          wx.showToast({  
            title: '识别失败',  
            icon: 'error',  
            duration: 2000  
          }) 
        }
      }
    })
  },

  // 输入车牌号
  openclose:function(e){
    var _this = this;
    let lid = this.data.optionindex;
    if(!lid){
      wx.showToast({
        title: '请选择方值',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    var type = e.currentTarget.dataset.type;
    _this.setData({
      car_type:type
    })
  },
  // 确认车牌号，开始计算
  carcodeAdd:function(e){
    var car_code = e.detail.value.car_code
    let lid = this.data.optionindex;
    console.log(lid)
    if(!car_code){
      wx.showToast({
        title: '请输入车牌号',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    if(!lid){
      wx.showToast({
        title: '请选择方值',
        icon: 'error',
        duration: 2000
      })
      return;
    }
    this.setData({
      car_code:car_code,
    })
    this.calculation();
  },

  // 计算
  calculation:function(e){
    let _this = this

    let code = _this.data.imgCode
    let list = _this.data.list
    let car_code = _this.data.car_code
    let lid = _this.data.optionindex;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: 'https://www.shumutou.com/api/index/math',
      method:'post',
      dataType:JSON,
      data: {
        code:code,
        list:list,
        lid:lid,
        car:car_code
      },
      success:(res)=>{
        wx.hideLoading()
        res = JSON.parse(res.data);
        console.log(res);
        if(res.success == 1){
          // dosomthin
          _this.setData({
            squareNumber:res.data,
            car_type:2
          })
        }else{
          wx.showToast({  
            title: res.tips,  
            icon: 'error',  
            duration: 2000  
          }) 
        }
      }
    })
  },

  // 获取图片信息
  initImg:function(url) {  //定位图片左上角的坐标
    let _this = this;
    wx.getImageInfo({
      src: url,
      success(resopne) {
        console.log(resopne);
        let imageWidth = _this.data.width
        let imageHeight = parseFloat(_this.data.width/resopne.width*resopne.height);

        _this.setData({
          originImg:{
            url:url,
            width:imageWidth,
            height:imageHeight
          },
          stv:{
            offsetX: 0,
            offsetY: 0,
            zoom: false, //是否缩放状态
              distance: 0,  //两指距离
              scale: 1,  //缩放倍数
              rotate: 0
          }
        })
      }
    })
  },

  // 触摸事件开始
  touchstartCallback: function (e) {
    if (e.touches.length === 1) { //一指触控
      let { clientX, clientY } = e.touches[0];
      this.startX = clientX; //手指起始点横坐标
      this.startY = clientY; //手指起始点纵坐标
      this.touchStartEvent = e.touches; 
    } else { //多指
      let xMove = e.touches[1].clientX - e.touches[0].clientX; //两手指起始点横坐标差
      let yMove = e.touches[1].clientY - e.touches[0].clientY; //两手指起始点纵坐标差
      let distance = Math.sqrt(xMove * xMove + yMove * yMove); //两手指距离
      twoPoint.x1 = e.touches[0].pageX * 2 //第一个手指距离文档左上角的x距离
      twoPoint.y1 = e.touches[0].pageY * 2 //第一个手指距离文档左上角的y距离
      twoPoint.x2 = e.touches[1].pageX * 2 //第二个手指距离文档左上角的x距离
      twoPoint.y2 = e.touches[1].pageY * 2 //第二个手指距离文档左上角的y距离
      this.setData({
        'stv.distance': distance,
        'stv.zoom': true, //缩放状态
      })
    }
  },
  // 增加圆
  adddelete:function(e){
    var _this = this;
    var list = this.data.list;
    var type = e.currentTarget.dataset.type;

    var newarr = [0,0,0];
    if(type == 1){
      list.push(newarr);
    }else{
      list.pop();
    }
    console.log(list);
    _this.setData({
      list:list,
      imgCount:list.length
    })
  },
  // 图片添加圆
  addYuan:function(e){
    let _this = this;
    if(_this.data.checkYuan == false){
      let list = _this.data.list
      var r = parseFloat(_this.data.originImg.width/20);
      var y = parseFloat(e.touches[0].clientY - _this.data.stv.offsetY - r -45);
      var x = parseFloat(e.touches[0].clientX - _this.data.stv.offsetX - r);
      if(y < 0 || y > _this.data.originImg.height){
        return;
      }
      if(x < 0 || x > _this.data.originImg.width){
        return;
      }

      if(list[0][3]){
        var rr = list[0][3] / list[0][2];
        var newl = r*rr
        newl = Math.round((newl + Number.EPSILON) * 100) / 100;
        var newYuan = [x,y,r,newl]
      }else{
        var newYuan = [x,y,r];
      }
      
      list = _this.data.list;
      list.push(newYuan);
      var length = list.length;
      _this.setData({
        list:list,
        checkYuan:length,
        chackYuanInfo:newYuan,
        imgCount:list.length
      })
    }
  },
  // 选中某个圆
  selectYuan:function(e){
    let checkYuan = e.currentTarget.dataset.type + 1
    var list = this.data.list;
    this.setData({
      checkYuan:checkYuan,
      chackYuanInfo:list[e.currentTarget.dataset.type]
    })
  },
  // 修改X轴位置
  changeX:function(e){
    var num = e.currentTarget.dataset.num;
    var value = e.detail.value;
    this.changeImg('x',num,value)
  },
  // 修改Y轴位置
  changeY:function(e){
    var num = e.currentTarget.dataset.num;
    var value = e.detail.value;
    this.changeImg('y',num,value)
  },
  // 修改半径
  changeR:function(e){
    var num = e.currentTarget.dataset.num;
    var value = e.detail.value;
    this.changeImg('r',num,value)
  },
  //图片手势动态缩放
  touchmoveCallback: function (e) {
    let _this = this
    fn(_this, e)
  },
  touchendCallback: function (e) {
    //触摸结束
    if (e.touches.length === 0) { 
      this.setData({
        'stv.zoom': false, //重置缩放状态
      })
    }
  },

  // 确认选中圆
  formSubmit: function (e) {
    let _this = this
    var list = _this.data.list;
    let checkYuan = _this.data.checkYuan - 1;
    let rr = _this.data.chackYuanInfo[2];
    var l = e.detail.value.l
    let rl = l / rr;

    if(l != ''){
      if(list[checkYuan][3] != l){
        var newList=[]
        for(var i=0;i<list.length;i++){
          var newls = rl*list[i][2];
          newls = Math.round((newls + Number.EPSILON) * 100) / 100;
          var arr = [list[i][0],list[i][1],list[i][2],newls]
          newList.push(arr)
        }
        _this.setData({
          list:newList
        })
      }
    }
    _this.setData({
      checkYuan:false,
      chackYuanInfo:[],
    })
  },
  // 删除圆
  removeYuan:function(){
    var _this = this;
    var chackYuan = this.data.checkYuan;
    var num = chackYuan -1;
    var list = this.data.list;
    list.splice(num,1);
    this.setData({
      list:list,
      checkYuan:false,
      chackYuanInfo:[],
      imgCount:list.length
    })
  },
  // 移动圆
  changeImg:function(type,num,value){
    var _this = this;
    var chackYuanInfo = _this.data.chackYuanInfo
    if(type == 'x'){
      chackYuanInfo = [value,chackYuanInfo[1],chackYuanInfo[2]]
    }else if(type == 'y'){
      chackYuanInfo = [chackYuanInfo[0],value,chackYuanInfo[2]]
    }else if(type == 'r'){
      if(!chackYuanInfo[3]){
        chackYuanInfo = [chackYuanInfo[0],chackYuanInfo[1],value]
      }else{
        var rr = chackYuanInfo[3] / chackYuanInfo[2];
        var newl = value*rr
        newl = Math.round((newl + Number.EPSILON) * 100) / 100;
        chackYuanInfo = [chackYuanInfo[0],chackYuanInfo[1],value,newl]
      }
    }
    var num = num - 1;
    var playStatus = "list[" + num + "]";
    _this.setData({
  　　[playStatus]:chackYuanInfo,
      chackYuanInfo:chackYuanInfo
    });
    console.log(this.data.list);
  },
  // 数据记录
  history:function(){
    let uid = wx.getStorageSync("uid");
    if(uid == undefined || uid == ''){
      wx.navigateTo({
        url:'/pages/login/login',
      })
    }else{
      wx.navigateTo({
        url:'/pages/order/order',
      })
    }
  },
  // 添加次数
  fre_click:function()
  {
    let uid = wx.getStorageSync("uid");
    if(uid == undefined || uid == ''){
      wx.navigateTo({
        url:'/pages/login/login',
      })
    }else{
      wx.navigateTo({
        url:'/pages/money/money',
      })
    }
  },
  //选择方数
  bindPickerChange:function(e){
    let option = this.data.option;
    this.setData({
      optionindex: option[e.detail.value]['id'],
      optiontitle: option[e.detail.value]['name']
    })
  },
  // 重新选择
  closeImg:function(){
    this.setData({
      list:[],
      btnType:1,
      imgCount:0,
      squareNumber:0,
      car_type:2,
      car_code:'',
      frequency:0,
      checkYuan:false,
      imagePath:'',
      width: device.windowWidth,                //剪裁框的宽度
      height: device.windowHeight / 2,//剪裁框的长度
      originImg: null,                                //存放原图信息
      stv: {
        offsetX: 0,                                   //剪裁图片左上角坐标x
        offsetY: 0,                                   //剪裁图片左上角坐标y
        zoom: false,                                  //是否缩放状态
        distance: 0,                                  //两指距离
        scale: 1,                                     //缩放倍数
        rotate: 0                                     //旋转角度
      },
    })
  }
})













var throttle = function (fn, delay, mustRun) {
  var timer = null,
    previous = null;

  return function () {
    var now = +new Date(),
      context = this,
      args = arguments;
    if (!previous) previous = now;
    var remaining = now - previous;
    if (mustRun && remaining >= mustRun) {
      fn.apply(context, args);
      previous = now;
    } else {
      clearTimeout(timer);
      timer = setTimeout(function () {
        fn.apply(context, args);
      }, delay);

    }
  }
}

var touchMove = function (_this, e) {
  //触摸移动中
  if (e.touches.length === 1) {
    //单指移动
    if (_this.data.stv.zoom) {
      //缩放状态，不处理单指
      return;
    }
    let { clientX, clientY } = e.touches[0];
    let offsetX = clientX - _this.startX; //移动 
    let offsetY = clientY - _this.startY; //移动
    _this.startX = clientX; //更新起始点坐标
    _this.startY = clientY; //更新起始点坐标
    let { stv } = _this.data;
    stv.offsetX += offsetX;
    stv.offsetY += offsetY;
    stv.offsetLeftX = -stv.offsetX;
    stv.offsetLeftY = -stv.offsetLeftY;
    _this.setData({
      stv: stv
    });

  } else if (e.touches.length === 2) {
    //计算旋转
    let preTwoPoint = JSON.parse(JSON.stringify(twoPoint))
    // twoPoint.x1 = e.touches[0].pageX * 2
    // twoPoint.y1 = e.touches[0].pageY * 2
    // twoPoint.x2 = e.touches[1].pageX * 2

    function vector(x1, y1, x2, y2) {
      this.x = x2 - x1;
      this.y = y2 - y1;
    };

    //计算点乘
    function calculateVM(vector1, vector2) {
      return (vector1.x * vector2.x + vector1.y * vector2.y) / (Math.sqrt(vector1.x * vector1.x + vector1.y * vector1.y) * Math.sqrt(vector2.x * vector2.x + vector2.y * vector2.y));

    }
    //计算叉乘
    function calculateVC(vector1, vector2) {
      return (vector1.x * vector2.y - vector2.x * vector1.y) > 0 ? 1 : -1;
    }

    let vector1 = new vector(preTwoPoint.x1, preTwoPoint.y1, preTwoPoint.x2, preTwoPoint.y2);
    let vector2 = new vector(twoPoint.x1, twoPoint.y1, twoPoint.x2, twoPoint.y2);
    let cos = calculateVM(vector1, vector2);
    let angle = Math.acos(cos) * 180 / Math.PI;

    let direction = calculateVC(vector1, vector2);
    let _allDeg = direction * angle;


    // 双指缩放
    let xMove = e.touches[1].clientX - e.touches[0].clientX; //两指x距离
    let yMove = e.touches[1].clientY - e.touches[0].clientY; //两指y距离
    let distance = Math.sqrt(xMove * xMove + yMove * yMove); //两指距离

    let distanceDiff = distance - _this.data.stv.distance; //两指距离变化
    let newScale = _this.data.stv.scale + 0.005 * distanceDiff; //得到缩放倍数

    if (Math.abs(_allDeg) > 1) {
      _this.setData({
        'stv.rotate': _this.data.stv.rotate + _allDeg
      })
    } else {
      //双指缩放
      let xMove = e.touches[1].clientX - e.touches[0].clientX;
      let yMove = e.touches[1].clientY - e.touches[0].clientY;
      let distance = Math.sqrt(xMove * xMove + yMove * yMove);

      let distanceDiff = distance - _this.data.stv.distance;
      let newScale = _this.data.stv.scale + 0.005 * distanceDiff;
      if (newScale < 0.2 || newScale > 2.5) {
        return;
      }
      _this.setData({
        'stv.distance': distance,
        'stv.scale': newScale,
      })
    }
  } else {
    return;
  }
}

//为touchMove函数节流
const fn = throttle(touchMove, 10, 10);